<template>
	<view @tap.stop="handleSendVerCode">
		<template v-if="timer">
			{{ `${time}s ${afterText}` }}
		</template>
		<template v-else>
			{{ beforeText }}
		</template>
	</view>
</template>
<script>
	import {
		validate
	} from '@/common/utils/index'
	import {
		IS_DEV
	} from '@/common/config.js'
	export default {
		name: 'benben-send-verification-code',
		props: {
			phone: {
				//发送短信的验证码
				type: [String, Number],
				default: '',
			},
			email: {
				//发送短信的验证码
				type: [String, Number],
				default: '',
			},
			area_code: {
				type: [String, Number],
				default: '',
			},
			type: {
				//发送短信类型
				type: [String, Number],
				default: 1,
			},
			afterText: {
				//发送成功后展示的文本
				type: [String, Number],
				default: '后重新获取',
			},
			beforeText: {
				//未发送时展示的文本
				type: [String, Number],
				default: '请发送验证码',
			},
		},
		computed: {},
		data() {
			return {
				time: 60, // 倒计时60S,@Number
				timer: null, // 计时器,@Function
			}
		},
		methods: {
			async handleSendVerCode() {
				// 从this里结构出来phone
				let {
					type,
					phone,
					area_code,
					email
				} = this
				// 验证手机号strat
				if (!area_code) {
					this.$message.info('请选择区号')
					return false
				}
				if (!phone) {
					this.$message.info('请输入手机号')
					return false
				}

				let noPhone = !validate(phone, 'phone')
				let noemail = !validate(phone, 'email')
				// if (noPhone && noemail) {
				//   return this.$message.info(global.i18n.t('请输入正确账号'))
				// }
				// 验证手机号 end
				// 如果有倒计时，return false
				if (this.flag) return false
				this.flag = true
				uni.showLoading({
					title: '发送中...',
					mask: true,
				})
				/**
				 * @desc 请求验证码接口
				 * @param {Object} {} - 参数
				 * @param {Boolean} {}.is_test - 是否是测试环境
				 * @param {String} {}.mobile - 手机号
				 * @param {String} {}.type - 类型
				 */
				try {
					let res = await this.$api.post(global.apiUrls.getcode, {
						is_test: IS_DEV != 0 ? 1 : 0,
						mobile: phone,
						email: email,
						type: type,
						area_code: area_code
					})
					uni.hideLoading()
					if (res.data.code != 1) {
						this.$message.info(res.data.msg)
						this.flag = false
						return
					}
					// 清除倒计时,防抖作用
					this.timer && clearInterval(this.timer)
					this.timer = setInterval(() => {
						if (this.time == 1) {
							//倒计时结束就清楚这个倒计时
							clearInterval(this.timer)
							this.timer = null
							this.flag = false
							this.time = 60 // 倒计时60s
							return
						}
						this.time--
					}, 1000)
					// 向用户发送提示
					if (IS_DEV != 0) {
						this.$message.info(res.data.data.code)
					} else {
						this.$message.info(global.i18n.t('验证码发送成功'))
					}
				} catch (error) {
					this.flag = false
					uni.hideLoading()
					// 接口错误打印错误
					console.log(error)
				}
			},
		},
		created() {},
	}
</script>

<style lang="scss" scoped></style>